/**
 * 
 */
package control;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import dao.NovelDao;
import model.Novel;

/**
 * @author Administrator
 *
 */
public class catchNovelThread extends Thread {

	private static Integer count = 0;
	private String html;
	private CountDownLatch startGate;
	private CountDownLatch endGate;
	
	

	/**
	 * @param html
	 * @param startGate
	 * @param endGate
	 */
	public catchNovelThread(String html, CountDownLatch startGate, CountDownLatch endGate) {
		this.html = html;
		this.startGate = startGate;
		this.endGate = endGate;
	}

	/**
	 * 发起http get请求获取网页源代码 
	 * */
	private String httpRequest(String requestUrl) {
		StringBuffer sb = null;
		BufferedReader br = null;
		InputStreamReader isr = null;
		InputStream is = null;
		HttpURLConnection huc = null;		
		
		try {
			// 建立get请求
			URL url = new URL(requestUrl);
			huc = (HttpURLConnection) url.openConnection();
			huc.setDoInput(true);
			huc.setRequestMethod("POST");
			huc.setConnectTimeout(30000);  
			huc.setReadTimeout(30000);  

			// 获取输入流
			is = huc.getInputStream();
			isr = new InputStreamReader(is, "gbk");
			br = new BufferedReader(isr);

			// 从输入流读取结果
			sb = new StringBuffer();
			String str = null;
			while ((str = br.readLine()) != null) {
				sb.append(str);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 释放资源
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (huc != null) {
				huc.disconnect();
			}
		}
		
		return sb.toString();
	}
	
	/**
	 * 过滤掉html字符串中无用的信息
	 * */
	private String htmlFiter(String html) {
		StringBuffer sBuffer = new StringBuffer();
		String str1 = "";
		sBuffer.append(str1);
		
		Pattern p = Pattern.compile("(.*)(<h1>)(.*)(</h1>)(.*)");
		Matcher m = p.matcher(html);
		if (m.matches()) {
			str1 = m.group(3);
			sBuffer.append(str1);
		}
//		System.out.println(sBuffer);
		return sBuffer.toString();
 	}
	public synchronized void saveToDatabase(ArrayList<String> reHtml, ArrayList<String> reNovelName) {
		Novel n = null;
		NovelDao nDao = new NovelDao();
		List<Novel> nlist = new ArrayList<Novel>();
		
		for (int i = 0; i < reHtml.size(); i++) {
			n = new Novel();
			n.setNovelName(reNovelName.get(i));
			n.setNovelURL(reHtml.get(i));
			nlist.add(n);
//			System.out.println(n);
		}

		try {
			nDao.addNovel(nlist);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void getHttpContentInfo(String html) {
		String url = html;
		String novelName = null;
		ArrayList<String> reHtml = new ArrayList<String>();
		String allHtml = null;
		ArrayList<String> reNovelName = new ArrayList<String>();
		
		for (int i = 0; i < 5; i++) {			
			synchronized(this){			
				html = url + (count++) + "/";
				System.out.println(html);
			}
				reHtml.add(html);
				// 调用第一个方法，获取html字符串
				allHtml = httpRequest(html);
//			System.out.println(allHtml);
				// 调用第二个方法，过滤掉无用的信息
				novelName = htmlFiter(allHtml);
//			System.out.println(novelName);
				reNovelName.add(novelName);
		}
		saveToDatabase(reHtml, reNovelName);
	}
	
	@Override
	public void run() {
        try {
        	getHttpContentInfo(html);
            startGate.await();
            Random random = new Random();
            int num = random.nextInt(500) + 500;
            System.out.println(Thread.currentThread().getName() + " start and sleep: " + num + "ms");
            Thread.sleep(num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            endGate.countDown();
        }
    }
}
